package com.ibl.rover.lite.client.Activity;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.RoverLiteClientActivity;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.Utility.OrderExport;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.CustomerBean;
import com.ibl.rover.lite.common.bean.DefaultRouteBean;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductOrderBean;
import com.ibl.rover.lite.common.bean.RouteBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;

public class CustomerRouteActivity extends Activity implements OnClickListener,
		OnCheckedChangeListener {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private Spinner routeSpinner = null;
	ProgressDialog progressDlg = null;
	final Handler handler = new Handler();
	protected ArrayList<CharSequence> selectedRouteDefault;
	private int selectedIndex = -1;
	private DefaultRouteBean defaultRouteBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.customer_route);
			initialiazeResources();
		} catch (Exception e) {
			logger.logException("OnCreate Exception", e);
		}
	}

	private void initialiazeResources() {
		try {
			roverApp = (ApplicationContext) getApplication();
			((TextView) findViewById(R.id.txt_tso_code_value))
					.setText(roverApp.loggedUser.getUserName());

			((TextView) findViewById(R.id.txt_date_value))
					.setText(getCurrentDate());

			selectedRouteDefault = new ArrayList<CharSequence>();
			manager = roverApp.getDatabaseManager();
			routeSpinner = (Spinner) findViewById(R.id.route_spinner);

			ArrayAdapter<CharSequence> routeAdapter = new ArrayAdapter<CharSequence>(
					this, android.R.layout.simple_spinner_item, getRouteInfo());

			routeAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			routeSpinner.setAdapter(routeAdapter);

			getDefaultRoute();

			if (defaultRouteBean == null) {
				RouteBean routeBean = getCurrentRoute(getCurrentDate());

				if (routeBean != null) {
					int routePosition = routeAdapter.getPosition(routeBean
							.getCode().trim());
					routeSpinner.setSelection(routePosition);
				}
			} else {
				int routePosition = routeAdapter.getPosition(defaultRouteBean
						.getRouteCode().trim());
				routeSpinner.setSelection(routePosition);
			}

			((Button) findViewById(R.id.submit)).setOnClickListener(this);
			((Button) findViewById(R.id.sales_booking))
					.setOnClickListener(this);
		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("initialiazeResources", e);
		}
	}

	/**
	 * 
	 * @return Route Values
	 */
	private String[] getRouteInfo() {
		String[] routeNumber = null;
		Cursor cursor = null;
		try {
			cursor = manager.executeDistinctSQL(RouteBean.class,
					new String[] { RouteBean.COL_CODE });

			cursor.moveToFirst();
			routeNumber = new String[cursor.getCount()];
			int i = 0;
			while (!cursor.isAfterLast()) {
				routeNumber[i++] = cursor.getString(0).trim();
				cursor.moveToNext();
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("getRouteInfo Exception", e);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return routeNumber;

	}

	private RouteBean getCurrentRoute(String currentDate) {
		try {
			Criteria<RouteBean> criteria = manager
					.generateCriteria(RouteBean.class);

			criteria.addRestriction(RouteBean.COL_DAY, Operators.isEqual,
					(currentDate + " 00:00:00.0").toString().trim());

			List<RouteBean> routelist = criteria.execute();
			if (routelist.size() > 0)
				return routelist.get(0);
			else
				return null;
		} catch (Exception e) {
			logger.logException("Get Current Route", e);
		} finally {

		}
		return null;
	}

	/**
	 * 
	 * @return the Current date of Mobile
	 */
	public String getCurrentDate() {
		logger.log("[START] Get Current Date....");

		Date date = Calendar.getInstance().getTime();
		DateFormat formatter = new SimpleDateFormat(roverApp.getAppParams()
				.getDebugDateFormat());
		String today = formatter.format(date);

		logger.log("[END] Get Current Date....");
		return today;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.submit:
			searchCustoemr();
			break;
		case R.id.sales_booking:
			salesBooking();
			break;

		default:
			break;
		}

	}

	private void salesBooking() {
		try {

			roverApp.getViewContext().put(RoverConstants.CURRENT_CUSTOMER,
					getSelectedCustomerBean());
			isCustomerOrder();
			Intent intent = new Intent(this, SalesBookingActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("salesBooking Exception ", e);
		}
	}

	private void searchCustoemr() {
		try {

			String progMsg = getResources()
					.getString(R.string.common_searching);
			progressDlg = new ProgressDialog(this);
			progressDlg.setMessage(progMsg);
			progressDlg.setTitle(R.string.common_wait);
			progressDlg.setCancelable(false);
			progressDlg.show();

			Criteria<CustomerBean> criteria = manager
					.generateCriteria(CustomerBean.class);

			criteria.addRestriction(CustomerBean.COL_ROUTE_NUMBER,
					Operators.isEqual, routeSpinner.getSelectedItem()
							.toString());

			String searchAddress = ((EditText) findViewById(R.id.id_filter_val))
					.getText().toString();
			if (!searchAddress.equals("")) {
				criteria.addRestrictionWithAnd(CustomerBean.COL_NAME,
						Operators.isLike, "%" + searchAddress + "%");
			}

			criteria.setOrderBy(CustomerBean.COL_POSITION, true);
			final List<CustomerBean> customerList = criteria.execute();
			roverApp.showMessage("Result Found :" + customerList.size(),
					Toast.LENGTH_LONG);

			(new Thread(new Runnable() {

				@Override
				public void run() {
					selectedIndex = -1;
					// }

					// updateRetailerSearchTable(retailerList);
					handler.post(new Runnable() {

						@Override
						public void run() {
							buildRouteCustomerTable(customerList);

							progressDlg.dismiss();

							// finish();
						}
					});
				}
			})).start();

			// buildRouteCustomerTable(customerList);
			selectedIndex = -1;
			((Button) findViewById(R.id.sales_booking)).setEnabled(false);
		} catch (Exception e) {
			logger.logException("Search Custiomer ", e);
		}

	}

	private void buildRouteCustomerTable(List<CustomerBean> custoemrList) {
		try {
			TableLayout retailersTablereouteCustromerTable = (TableLayout) findViewById(R.id.route_customer_table);
			int textColor = getResources().getColor(
					R.color.table_item_text_color);
			if (retailersTablereouteCustromerTable.getChildCount() > 1) {
				retailersTablereouteCustromerTable.removeViews(1,
						retailersTablereouteCustromerTable.getChildCount() - 1);
			}
			LayoutParams otherParams = new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

			otherParams.setMargins(1, 0, 0, 1);
			TableRow row;
			for (CustomerBean customerBean : custoemrList) {
				row = new TableRow(this);
				row.setTag(customerBean);

				CheckBox selectedCustomer = new CheckBox(this);
				selectedCustomer.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				selectedCustomer.setPadding(2, 0, 2, 0);

				selectedCustomer.setOnCheckedChangeListener(this);
				// selectedCustomer.setButtonDrawable(R.drawable.checkbox);
				row.addView(selectedCustomer, otherParams);

				TextView txtCustomerShopname = new TextView(this);
				txtCustomerShopname.setTextAppearance(this,
						R.style.table_item_font);
				if (isCustomerOrder(customerBean.getCode())) {
					row.setBackgroundResource(R.color.table_visited_ordered_bg);
					txtCustomerShopname.setText(customerBean.getName() + "*");
				} else {
					txtCustomerShopname.setText(customerBean.getName());
				}
				txtCustomerShopname.setGravity(Gravity.LEFT);

				txtCustomerShopname.setPadding(5, 0, 5, 0);
				txtCustomerShopname.setTextColor(textColor);

				row.addView(txtCustomerShopname, otherParams);

				CheckBox actionButtion = new CheckBox(this);

				actionButtion.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				actionButtion.setPadding(2, 0, 2, 0);
				actionButtion.setButtonDrawable(R.drawable.view);
				actionButtion.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View view) {
						TableRow row = (TableRow) view.getParent();
						CustomerBean customerBean = (CustomerBean) row.getTag();

						roverApp.getViewContext().put(
								RoverConstants.CURRENT_CUSTOMER, customerBean);

						CustomerRouteActivity.this.getCustomerDetail();

					}
				});

				row.addView(actionButtion, otherParams);
				retailersTablereouteCustromerTable.addView(row);
				retailersTablereouteCustromerTable.invalidate();
			}

		} catch (Exception e) {
			logger.logException("Search Cusetomer", e);
		}

	}

	@Override
	public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
		try {
			if (checked) {
				CheckBox checkBox = (CheckBox) compoundButton;
				TableRow row = (TableRow) checkBox.getParent();
				TableLayout tableLayout = (TableLayout) row.getParent();
				int tempIndex = selectedIndex;
				selectedIndex = tableLayout.indexOfChild(row);
				if (tempIndex != -1 && selectedIndex != tempIndex) {
					((CheckBox) ((TableRow) tableLayout.getChildAt(tempIndex))
							.getChildAt(0)).setChecked(false);
				}
				((Button) findViewById(R.id.sales_booking)).setEnabled(true);
				selectedIndex = tableLayout.indexOfChild(row);
			} else {
				selectedIndex = -1;
				((Button) findViewById(R.id.sales_booking)).setEnabled(false);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("", e);
		}
	}

	/**
	 * Get Customer Details
	 */
	public void getCustomerDetail() {
		try {
			Intent intent = new Intent(this, CustomerDetailActivity.class);
			startActivityForResult(intent, 1);
		} catch (Exception e) {
			logger.logException("Get Customer Detail ", e);
		}
	}

	private CustomerBean getSelectedCustomerBean() {
		try {
			TableLayout retailersTablereouteCustromerTable = (TableLayout) findViewById(R.id.route_customer_table);

			TableRow row = (TableRow) retailersTablereouteCustromerTable
					.getChildAt(selectedIndex);
			CustomerBean customerBean = (CustomerBean) row.getTag();
			return customerBean;
		} catch (Exception e) {
			logger.logException("getSelectedCustomerBean Exception", e);
		}
		return null;
	}

	private void isCustomerOrder() {
		try {
			Criteria<OrderBean> criteria = manager
					.generateCriteria(OrderBean.class);
			criteria.addRestriction(OrderBean.COL_CUSTOMER_CODE,
					Operators.isEqual, getSelectedCustomerBean().getCode());
			List<OrderBean> orderList = criteria.execute();
			if (orderList.size() > 0) {
				OrderBean orderBean = orderList.get(0);
				Criteria<ProductOrderBean> productOrderBeanCriteria = manager
						.generateCriteria(ProductOrderBean.class);

				productOrderBeanCriteria.addRestriction(
						ProductOrderBean.COL_ORDER_KEY, Operators.isEqual,
						orderBean.getOrderId());

				List<ProductOrderBean> productOrderBeanList = productOrderBeanCriteria
						.execute();
				List<ProductBean> productBeansList = new ArrayList<ProductBean>();
				List<String> productBeansQuantityList = new ArrayList<String>();

				if (productOrderBeanList.size() > 0) {
					Criteria<ProductBean> searchProduct = manager
							.generateCriteria(ProductBean.class);
					searchProduct.addRestriction(ProductBean.COL_PRODUCT_CODE,
							Operators.isEqual, productOrderBeanList.get(0)
									.getProductCode());
					productBeansQuantityList.add(productOrderBeanList.get(0)
							.getQuantity());
					for (int i = 1; i < productOrderBeanList.size(); i++) {
						searchProduct.addRestriction(
								ProductBean.COL_PRODUCT_CODE,
								Operators.isEqual, productOrderBeanList.get(i)
										.getProductCode());
						productBeansQuantityList.add(productOrderBeanList
								.get(i).getQuantity());
					}
					productBeansList = searchProduct.execute();

					OrderBookingLine orderBookingLine = new OrderBookingLine();
					orderBookingLine.setProductBeanList(productBeansList);
					orderBookingLine.setOrderAmount(orderBean.getAmount());
					orderBookingLine
							.setProductQuantitylist(productBeansQuantityList);
					roverApp.getViewContext().put(
							RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS,
							orderBean);
					roverApp.getViewContext()
							.put(RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS_BOOKIG_LINE,
									orderBookingLine);
				}

			}

		} catch (Exception e) {
			logger.logException("iS Customer Order Exception", e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.rover_lite_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.retailer_products:
			getProductReport();
			return true;

		case R.id.retailer_abouts:
			getAbouts();
			return true;

		case R.id.retailer_orders:
			getOrderReport();
			return true;
		case R.id.retailer_sync:
			getSYncForm();
			return true;
		case R.id.retailer_logout:
			getlogOut();
			return true;
		case R.id.retailer_order_summary:
			getOrderSummary();
			return true;
		case R.id.default_route:
			showRoute(getRouteInfo());
			return true;
		case R.id.retailer_reset:
			isOrderSync();
			return true;
		case R.id.export_file:
			exportOrderFile();
			return true;
		default:
			return super.onOptionsItemSelected(item);

		}
	}

	private void exportOrderFile() {
		try {
			OrderExport export=new OrderExport(roverApp);
			export.generateCsvFile("Test");
		} catch (Exception e) {
			logger.logException("Export Order File Exception", e);
		}

	}

	private void getAbouts() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);

			builder.setMessage(
					"Rover Lite Software (c) 2011\n You can use this application on Behalf of IBL Employee.\n Powered by IBL.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

								}
							});
			builder.setTitle("About");
			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			logger.logException("Get About", e);
		}
	}

	private void getSYncForm() {
		try {
			Intent intent = new Intent(this, RoverSyncActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("get Products Report", e);
		}
	}

	private void getlogOut() {
		try {

			roverApp.deleteFile(roverApp.getUserName()
					+ ApplicationContext.CUR_USER_EXT);
			roverApp.setUserName(null);
			roverApp.loggedUser = null;
			Intent myIntent = new Intent(this, RoverLiteClientActivity.class);
			myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(myIntent);
			finish();
		} catch (Exception e) {
			logger.logException("get LogOut", e);
		}
	}

	private void getProductReport() {
		try {
			Intent intent = new Intent(this, ProductReportActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("get Products Report", e);
		}
	}

	private void getOrderReport() {
		try {
			Intent intent = new Intent(this, OrderReportActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("getOrderReport", e);
		}
	}

	private void getOrderSummary() {
		try {
			Intent intent = new Intent(this, RouteOrdeReportActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("getOrderReport", e);
		}
	}

	/**
	 * Show the Routes
	 */
	private void showRoute(String[] route) {
		try {
			logger.log("[Customer Route activity ] Show Route  START");
			final CharSequence[] routesArray = route;
			boolean[] checkedColours = new boolean[routesArray.length];
			int count = routesArray.length;
			// for (int i = 0; i < count; i++)
			// checkedColours[i] = selectedSkyType.contains(routesArray[i]);

			DialogInterface.OnClickListener skuTypesDialogListener = new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					selectedRouteDefault.clear();
					selectedRouteDefault.add(routesArray[arg1]);

				}
			};
			AlertDialog dialog;
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Select Default Route");
			selectedRouteDefault.add(routesArray[0]);
			builder.setSingleChoiceItems(routesArray, 0, skuTypesDialogListener);
			// builder.sets
			builder.setPositiveButton("Ok", new DialogButtonClickHandler());
			builder.setNegativeButton("Cancel", new DialogButtonClickHandler());

			dialog = builder.create();

			dialog.show();
			logger.log("[Add Retailer ] Show sku tyoes END");
		} catch (Exception e) {
			logger.logException("[Add Retailer ] Show sku tyoes EXCEPTION", e);
		}
	}

	public class DialogButtonClickHandler implements
			DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int clicked) {
			switch (clicked) {
			case DialogInterface.BUTTON_POSITIVE:
				saveDefaultRouteBean();
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				selectedRouteDefault.clear();
				break;

			}
		}
	}

	private void saveDefaultRouteBean() {
		try {
			String routDefault = selectedRouteDefault.get(0).toString();

			Criteria<RouteBean> criteria = manager
					.generateCriteria(RouteBean.class);

			criteria.addRestriction(RouteBean.COL_CODE, Operators.isEqual,
					routDefault);

			List<RouteBean> routelist = criteria.execute();
			if (routelist.size() > 0) {
				manager.executeScaler("DELETE FROM DEFAULT_ROUTE_BEAN");

				DefaultRouteBean defaultRouteBean = new DefaultRouteBean();
				defaultRouteBean.setRouteCode(routDefault);
				manager.saveBean(defaultRouteBean);

			}

		} catch (Exception e) {
			logger.logException("save DefaultRoute bean", e);
		}
	}

	private void getDefaultRoute() {
		try {
			List<DefaultRouteBean> defaultRouteBeanList = manager
					.findAllBean(DefaultRouteBean.class);
			if (defaultRouteBeanList.size() > 0)
				defaultRouteBean = defaultRouteBeanList.get(0);

		} catch (Exception e) {
			logger.logException("Get Default Route ", e);
		}
	}

	private void doHandleSuccess() {
		try {

			manager.executeScaler("DELETE FROM APP_SETUP_BEAN");
			manager.executeScaler("DELETE FROM CUSTOMER_BEAN");
			manager.executeScaler("DELETE FROM ORDER_BEAN");
			manager.executeScaler("DELETE FROM PRODUCT_BEAN");
			manager.executeScaler("DELETE FROM PRODUCT_CATEGROY");
			manager.executeScaler("DELETE FROM PRODUCT_ORDER_BEAN");
			manager.executeScaler("DELETE FROM ROUTE_BEAN");
			manager.executeScaler("DELETE FROM USER_BEAN");
			resetDevice();
			// roverApp.getViewContext().clear();
			roverApp.showMessage("Order reset Sucessfully", Toast.LENGTH_LONG);
			// finish();
			//
			// Intent intent = new Intent(RoverSyncActivity.this,
			// RoverLiteClientActivity.class);
			// startActivity(intent);
		} catch (Exception e) {
			logger.logException("doHandleSuccess Exception", e);
		}

	}

	private void resetDevice() {
		try {
			 manager.executeScaler("DELETE FROM APP_SETUP_BEAN");
			 manager.executeScaler("DELETE FROM CUSTOMER_BEAN");
			 manager.executeScaler("DELETE FROM ORDER_BEAN");
			 manager.executeScaler("DELETE FROM PRODUCT_BEAN");
			 manager.executeScaler("DELETE FROM PRODUCT_CATEGROY");
			 manager.executeScaler("DELETE FROM PRODUCT_ORDER_BEAN");
			 manager.executeScaler("DELETE FROM ROUTE_BEAN");
			 manager.executeScaler("DELETE FROM USER_BEAN");

			roverApp.deleteFile(roverApp.getUserName()
					+ ApplicationContext.CUR_USER_EXT);
			roverApp.setUserName(null);
			roverApp.loggedUser = null;
			roverApp.getViewContext().clear();
			Intent myIntent = new Intent(this, RoverLiteClientActivity.class);
			myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(myIntent);
			finish();
		} catch (Exception e) {
			logger.logException("get LogOut", e);
		}
	}

	private void isOrderSync() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					CustomerRouteActivity.this);
			builder.setMessage("Is Order Sync Sucessfully?")
					.setCancelable(false)
					.setPositiveButton(
							getResources().getString(R.string.common_yes),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									CustomerRouteActivity.this
											.doHandleSuccess();

								}
							})
					.setNegativeButton(
							getResources().getString(R.string.common_no),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			builder.setTitle("Alert");
			AlertDialog alert = builder.create();
			alert.show();

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("saveorder Detail", e);
		}
	}

	private boolean isCustomerOrder(String customerCode) {
		try {
			Criteria<OrderBean> criteria = manager
					.generateCriteria(OrderBean.class);
			criteria.addRestriction(OrderBean.COL_CUSTOMER_CODE,
					Operators.isEqual, customerCode);
			if (criteria.execute().size() > 0)
				return true;
		} catch (Exception e) {
			logger.logException("isCustomerOrder", e);
		}
		return false;
	}

}
